package com.xpec.c4.db.usertype;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.hibernate.HibernateException;

import com.ms.db.usertype.BasicToString;

/**
 * 把Map(Map<String,Integer>)转换为String<br>
 * 使用指定的分隔符，默认为";"
 * 
 * @author Bany
 * 
 */
public class MapStringIntegerToString extends BasicToString {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3328585751571709038L;

	@Override
	public int[] sqlTypes() {
		return CLOB_TYPES;
	}

	@Override
	public Class<?> returnedClass() {
		return Map.class;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		/*
		 * if (x == y) return true;
		 */
		if (x != null && y != null) {
			Map<?, ?> xMap = (Map<?, ?>) x;
			Map<?, ?> yMap = (Map<?, ?>) y;
			if (xMap.size() != yMap.size())
				return false;
			Set<?> keys = xMap.keySet();
			for (Object key : keys) {
				Object str1 = xMap.get(key);
				Object str2 = yMap.get(key);
				if (!str1.equals(str2))
					return false;
			}
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected String assemble(Object obj) {
		Map<String, Integer> map = (Map<String, Integer>) obj;
		StringBuffer strBuf = new StringBuffer();
		Set<String> keys = map.keySet();
		for (Object key : keys) {
			strBuf.append(key + SPLITTER);
			strBuf.append(String.valueOf(map.get(key)) + SPLITTER);
		}
		if (strBuf.length() > 0) {
			strBuf.setLength(strBuf.length() - 1);
		}
		return strBuf.toString();
	}

	@Override
	protected Object parse(String value) {
		if(value==null){
			return null;
		}
		Map<String, Integer> map = new HashMap<String, Integer>();
		if (value.length() <= 0) {
			return map;
		}
		String[] strs = value.split(SPLITTER);

		for (int i = 0; i < strs.length; i += 2) {
			map.put(strs[i], Integer.valueOf(strs[i + 1]));
		}
		return map;
	}

}
